import sys
from PyQt6.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout, QPushButton, QLineEdit, QMessageBox


class ListWidgetExample(QWidget):
    def __init__(self):
        super().__init__()

        # 创建垂直布局
        layout = QVBoxLayout()

        # 创建 QListWidget 对象
        self.list_widget = QListWidget(self)

        # 添加列表项
        items = ["Item 1", "Item 2", "Item 3", "Item 4"]
        for item in items:
            self.list_widget.addItem(item)

        # 创建输入框用于输入要添加的项
        self.input_box = QLineEdit(self)
        self.input_box.setPlaceholderText("输入要添加的项")

        # 创建添加按钮
        self.add_button = QPushButton("添加最后一项", self)
        self.add_button.clicked.connect(self.add_item)

        # 创建删除按钮
        self.delete_button = QPushButton("删除选中项", self)
        self.delete_button.clicked.connect(self.delete_item)

        # 连接双击信号到显示细节的槽函数
        self.list_widget.itemDoubleClicked.connect(self.show_item_index)

        # 将组件添加到布局中
        layout.addWidget(self.list_widget)
        layout.addWidget(self.input_box)
        layout.addWidget(self.add_button)
        layout.addWidget(self.delete_button)

        # 设置窗口布局
        self.setLayout(layout)

        # 设置窗口标题和大小
        self.setWindowTitle('QListWidget 示例')
        self.setGeometry(300, 300, 300, 200)

    def add_item(self):
        text = self.input_box.text()
        if text:
            self.list_widget.addItem(text)
            self.input_box.clear()

    def delete_item(self):
        current_item = self.list_widget.currentItem()
        if current_item:
            row = self.list_widget.row(current_item)
            self.list_widget.takeItem(row)

    def show_item_index(self, item):
        index = self.list_widget.row(item) + 1
        details = f"你双击的项是列表中的第 {index} 个"
        QMessageBox.information(self, "详细信息", details)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ListWidgetExample()
    window.show()
    sys.exit(app.exec())
    